import os
import subprocess
import math
import shutil

AUDIO_ROOT = 'audio'
OUTPUT_ROOT = 'audio_fast'
MAX_DURATION = 1800  # 30分钟，单位：秒
ALT_DURATION = 1740  # 29分钟，单位：秒

# 获取mp3文件时长（秒）
def get_mp3_duration(mp3_path):
    cmd = [
        'ffprobe', '-v', 'error', '-show_entries', 'format=duration',
        '-of', 'default=noprint_wrappers=1:nokey=1', mp3_path
    ]
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    try:
        return float(result.stdout.strip())
    except Exception:
        return None

# 生成atempo参数串联（ffmpeg单次支持0.5~2.0倍速）
def build_atempo_filters(speed):
    filters = []
    while speed > 2.0:
        filters.append('atempo=2.0')
        speed /= 2.0
    while speed < 0.5:
        filters.append('atempo=0.5')
        speed /= 0.5
    filters.append(f'atempo={speed:.5f}')
    return ','.join(filters)

def speedup_mp3(input_path, output_path, speed):
    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    atempo_filters = build_atempo_filters(speed)
    cmd = [
        'ffmpeg', '-y', '-i', input_path, '-filter:a', atempo_filters, '-vn', output_path
    ]
    subprocess.run(cmd, check=True)

def main():
    for root, dirs, files in os.walk(AUDIO_ROOT):
        for file in files:
            if not file.lower().endswith('.mp3'):
                continue
            rel_dir = os.path.relpath(root, AUDIO_ROOT)
            input_path = os.path.join(root, file)
            output_dir = os.path.join(OUTPUT_ROOT, rel_dir)
            output_path = os.path.join(output_dir, file)
            if os.path.exists(output_path):
                print(f"[跳过] 已存在: {output_path}")
                continue
            duration = get_mp3_duration(input_path)
            if duration is None:
                print(f"[错误] 获取时长失败: {input_path}")
                continue
            if duration <= MAX_DURATION:
                print(f"[拷贝] {input_path} -> {output_path} ({duration/60:.1f}分钟)")
                os.makedirs(os.path.dirname(output_path), exist_ok=True)
                shutil.copy2(input_path, output_path)
                continue
            # 计算加速倍数
            target = MAX_DURATION if duration/MAX_DURATION < duration/ALT_DURATION else ALT_DURATION
            speed = duration / target
            print(f"[加速] {input_path} -> {output_path}，倍速: {speed:.3f}")
            try:
                speedup_mp3(input_path, output_path, speed)
            except Exception as e:
                print(f"[错误] 加速失败: {input_path}，原因: {e}")

if __name__ == '__main__':
    main() 